package com.rainbow.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rainbow.entity.Token;
import com.rainbow.entity.User;
import com.rainbow.mapper.TokenMapper;
import com.rainbow.service.TokenService;
import com.rainbow.service.UserService;
import com.rainbow.utils.ApiUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author rainbow
 **/
@Service
public class TokenServiceImpl extends ServiceImpl<TokenMapper, Token> implements TokenService {

    @Autowired
    private UserService userService;

    @Override
    public Token createToken(Long userId) {
        // 过期时间
        Date expireDate = ApiUtils.getFutureTime(1);

        String token = generateToken();
        // 保存或者更新token
        Token token1 = new Token();
        token1.setUserId(userId);
        token1.setExpireTime(expireDate);
        token1.setUpdateTime(new Date());
        token1.setToken(token);

        saveOrUpdate(token1);


        return token1;
    }

    @Override
    public void expireToken(String username) {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        Assert.isNull(user, "用户名" + username + "不存在");

        Date date = new Date();

        Token token = new Token();
        token.setUserId(user.getId());
        token.setUpdateTime(date);
        token.setExpireTime(date);

        updateById(token);
    }

    @Override
    public Token queryByToken(String token) {
        return getOne(new QueryWrapper<Token>().eq("token", token).ge("expire_time", new Date()));
    }

    private String generateToken() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
